package web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import domain.Goods;
import domain.Order;
import domain.OrderList;
import factory.ServiceFactory;
import net.sf.json.JSONObject;
import util.FloatUtil;

/**
 * Servlet implementation class Shouyin
 */
@WebServlet("/shouyin.do")
public class Shouyin extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Shouyin() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String meth = request.getParameter("method");
		if (meth == null || meth.equals("")) {
			meth = "index";
		}
		switch (meth) {
		case "saoma":
			saoma(request, response);
			break;
		case "index":
			request.getRequestDispatcher("home.html").forward(request, response);
			break;
		case "createOrder":
			createOrder(request, response);
			break;
		default:
			break;
		}
	}

	private void saoma(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json;charset=utf-8");
		JSONObject json = new JSONObject();
		String txm = request.getParameter("txm");
		String slString = request.getParameter("sl");
		int sl = (slString == null || slString.equals("")) ? 0 : Integer.valueOf(slString);
		if (sl == 0 || txm == null || txm.equals("")) {
			json.put("status", 500);
			json.put("msg", "数量和条形码有误！");
		} else {
			Goods goods = ServiceFactory.getSerInstance().getOneGoodsInfo(txm);
			if (goods == null) {
				json.put("status", 400);
				json.put("msg", "尚未添加该商品信息，请先添加！");
			} else {
				if (goods.getNumber() < sl) {
					json.put("status", 502);
					json.put("msg", "该商品仅剩" + goods.getNumber() + "件，无法完成购买！");
				} else {
					json.put("status", 200);
					HashMap<Integer, Float> zkls = ServiceFactory.getSerInstance().getAllZk();
					float zj = zkls.get(goods.getZkl()) * goods.getPrice() * sl;
					json.put("dj", String.valueOf(goods.getPrice()));
					json.put("zj", String.valueOf(FloatUtil.floatSaveTwoD(zj)));
					json.put("name", goods.getName());
				}
			}
		}
		PrintWriter out = response.getWriter();
		out.print(json);
		out.close();
	}

	protected void createOrder(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String txms = request.getParameter("txms");
		String slString = request.getParameter("sls");
		String paystring = request.getParameter("type");
		List<String> txmList = new ArrayList<String>(txms.split(",").length);
		Collections.addAll(txmList, txms.split(","));
		List<String> slList = new ArrayList<String>(slString.split(",").length);
		Collections.addAll(slList, slString.split(","));
		Order order = new Order(0, 0, new Date(System.currentTimeMillis()), Integer.valueOf(paystring));
		int orderId = ServiceFactory.getSerInstance().addOrder(order);
		order.setId(orderId);
		double yj = 0;
		double ss = 0;
		HashMap<Integer, Float> zkls = ServiceFactory.getSerInstance().getAllZk();
		for (int i = 0, j = txmList.size(); i < j; i++) {
			Goods goods = ServiceFactory.getSerInstance().getOneGoodsInfo(txmList.get(i));
			goods.setNumber(goods.getNumber() - Integer.valueOf(slList.get(i)));
			double t1 = 0;
			t1 = FloatUtil.floatSaveTwoD(Integer.valueOf(slList.get(i)) * goods.getPrice());
			yj += t1;
			double t = 0;
			t = FloatUtil.floatSaveTwoD(goods.getPrice() * zkls.get(goods.getZkl()));
			t = FloatUtil.floatSaveTwoD(t * Integer.valueOf(slList.get(i)));
			ss += t;
			ServiceFactory.getSerInstance().updateGoods(goods);
			OrderList orderList = new OrderList(goods.getTxm(), Integer.valueOf(slList.get(i)),
					FloatUtil.floatSaveTwoD(t), order.getDate(), orderId);
			ServiceFactory.getSerInstance().addOrderList(orderList);
		}
		order.setYj(FloatUtil.floatSaveTwoD(yj));
		order.setSs(FloatUtil.floatSaveTwoD(ss));
		ServiceFactory.getSerInstance().updateOrder(order);
		response.setContentType("appliction/json;charset=utf-8");
		JSONObject json = new JSONObject();
		json.put("status", 200);
		PrintWriter out = response.getWriter();
		out.print(json);
		out.close();
	}

}
